package api

import (
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// 骑手与用户

type DMessage struct {
	UserId     string `json:"userId"  form:"userId" binding:"required"`
	DeliveryId string `json:"deliveryId"  form:"deliveryId" binding:"required"`
}

type Node struct {
	Conn *websocket.Conn
	Data chan []byte
}

var ClientMap = make(map[string]*Node, 0)
var Wsg sync.WaitGroup

func DChat(c *gin.Context) {
	var chat DMessage

	c.ShouldBind(&chat)
	id := chat.UserId
	deliveryId := chat.DeliveryId

	msg := &DMessage{
		UserId:     id,
		DeliveryId: deliveryId,
	}

	upgrader := websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
	upgrade, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := &Node{
		Conn: upgrade,
		Data: make(chan []byte, 100),
	}
	ClientMap[id+"_"+deliveryId] = node
	Wsg.Add(4)
	go read(node, msg)
	go send(node, msg)

}

func read(node *Node, msg *DMessage) {
	defer Wsg.Done()
	for {
		_, message, _ := node.Conn.ReadMessage()
		tr, ex := ClientMap[msg.UserId+"_"+msg.DeliveryId]
		if ex {
			tr.Data <- message
		}
	}
}
func send(node *Node, msg *DMessage) {
	defer Wsg.Done()
	select {
	case data := <-node.Data:
		err := node.Conn.WriteMessage(websocket.TextMessage, data)

		if err != nil {
			panic("消息发送失败")
			return
		}
	}
}

// 用户 与客服 聊天

type AMessage struct {
	UserId  string `json:"userId"  form:"userId" binding:"required"`
	AdminId string `json:"adminId"  form:"adminId" binding:"required"`
}

func AChat(c *gin.Context) {
	var chat AMessage

	c.ShouldBind(&chat)
	id := chat.UserId
	adminId := chat.AdminId

	msg := &AMessage{
		UserId:  id,
		AdminId: adminId,
	}

	upgrader := websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
	upgrade, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := &Node{
		Conn: upgrade,
		Data: make(chan []byte, 100),
	}
	ClientMap[id+"_"+adminId] = node
	Wsg.Add(4)
	go Aread(node, msg)
	go Asend(node, msg)
}

func Aread(node *Node, msg *AMessage) {
	defer Wsg.Done()
	for {
		_, message, _ := node.Conn.ReadMessage()
		tr, ex := ClientMap[msg.UserId+"_"+msg.AdminId]
		if ex {
			tr.Data <- message
		}
	}
}
func Asend(node *Node, msg *AMessage) {
	defer Wsg.Done()
	select {
	case data := <-node.Data:
		err := node.Conn.WriteMessage(websocket.TextMessage, data)

		if err != nil {
			panic("消息发送失败")
			return
		}
	}
}
